//url参数转obj
export function urlToObj(url) {
    var regex = /(\w+)=([^&#]*)/igm;
    var matchStr = null;
    var obj = {};
    while ((matchStr = regex.exec(url)) != null) {
        obj[matchStr[1]] = matchStr[2];
    }
    return obj;
};
//obj转为url参数
export function objToUrl(baseUrl, obj) {
    var parameters = "";
    var url = "";
    for (var key in obj) {
        parameters += key + "=" + obj[key] + "&";
    }
    parameters = parameters.replace(/&$/, "");
    if (/\?$/.test(baseUrl)) {
        url = baseUrl + parameters;
    } else {
        url = baseUrl.replace(/\/?$/, '?') + parameters;
    }
    return url;
};
//url参数转obj,若一个字段有多个值的话,返回数组
export function parseQueryString(url) {
    var obj = {};
    if (url) {
        url = url.replace(/#[^#]*$/, "");
        var index = url.indexOf("?");
        if (index != -1) {
            var queryStr = url.substr(index + 1);
            var marchResult = null;
            var regex = /(\w+)(=([^&#]+)?)?/g;
            while ((marchResult = regex.exec(queryStr)) != null) {
                if (marchResult[1] in obj) {
                    var values = obj[marchResult[1]];
                    if (values instanceof Array) {
                        values.push(marchResult[2] ? (marchResult[3] ? marchResult[3] : "") : null);
                        obj[marchResult[1]] = values;
                    } else {
                        var arr = [];
                        arr.push(values);
                        arr.push(marchResult[2] ? (marchResult[3] ? marchResult[3] : "") : null);
                        obj[marchResult[1]] = arr;
                    }
                } else {
                    obj[marchResult[1]] = marchResult[2] ? (marchResult[3] ? marchResult[3] : "") : null;
                }
            }
        }
    }
    return obj;
}

export default {
    urlToObj,
    objToUrl,
    parseQueryString
}